package com.jianganming.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.NettyRuntime;

public class NettyServer {

    public static void main(String[] args)throws Exception {
        //CPU核数
        System.out.println(NettyRuntime.availableProcessors());
        //主线程
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //工作线程
        EventLoopGroup workGroup = new NioEventLoopGroup();
        //启动对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //启动对象绑定线程组
        ChannelFuture future = serverBootstrap.group(bossGroup, workGroup)//设置线程租
                .channel(NioServerSocketChannel.class) //使用NIO通道
                .option(ChannelOption.SO_BACKLOG, 128)//设置队列个数
                .childOption(ChannelOption.SO_KEEPALIVE, true)//设置活动连接状态
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        //添加服务端处理器
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new NettyServerHandler());
                    }
                })
                .bind(9999).sync();
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    System.out.println("启动成功");
                }
            }
        });

        future.channel().closeFuture().sync();


        //serverBootstrap.clone();
    }
}
